<?php
namespace App\Http\Controllers;

use App\Models\Act;
use App\Models\Activity;
use App\Models\ActPrize;
use App\Models\ActType;
use App\Models\ActWinners;
use App\Models\Game;
use App\Models\GameGoods;
use App\Models\GamePrize;
use App\Models\GameType;
use App\Models\GameWinners;
use Illuminate\Http\Request;
use App\Models\ActPrizeSetting;
use \DB;
use App\Http\Requests\ActRequest;
use \Excel;
use Illuminate\Pagination\LengthAwarePaginator as lPaginator;

class GameController extends CommonController
{

    /**
     *获取列表
     */
    public function getIndex(Request $request)
    {
        $aIds = Game::with('activity')->orderBy('activity_id')->lists('activity_id')->toArray();
        $aIds = array_flip(array_flip($aIds));
        $lists = array();
        foreach($aIds as $k=>$v){
            $data = Game::with('activity')->where('activity_id', $v)->orderBy('activity_id')->first();
            if( isset($data->activity->subject)){
                $lists[$v]['activity_name'] = $data->activity->subject;
            }else{
                $lists[$v]['activity_name'] = '';
            }
            $lists[$v]['id'] = $v;
            $lists[$v]['games'] = Game::with('activity','type')->where('activity_id', $v)->orderBy('activity_id')->get();
        }

        $page = $request->input('page') ? $request->input('page') : 1;

        $paginator = new lPaginator(
            array_slice($lists, ($page - 1)*2, 10), count($lists), 10, $page, [
            'path'  => 'game',
//            'query' => array('uid' => $lists['uid'], 'chatroom_id' => $lists['chatroom_id']),
        ]);


        return view('game.index')->with("lists", $paginator)->with("actions", $this->actions)->with("wjtrUrl", $this->wjtrUrl);
    }


    /**
     * 执行一个搜索
     */
    public function search(Request $request)
    {
        $data = $request->input();
        $aIds = Game::with('activity')->orderBy('activity_id')->lists('activity_id')->toArray();
        if(isset($data['subject']) && $data['subject']!=''){
            $saIds = Activity::where('subject', 'like', '%'.trim($data['subject']).'%')->lists('id')->toArray();
            $aIds = array_intersect($aIds, $saIds);
        }

        $aIds = array_flip(array_flip($aIds));
//        dd($aIds);
        $lists = array();
        foreach($aIds as $k=>$v){
            $data = Game::with('activity')->where('activity_id', $v)->orderBy('activity_id')->first();
            if( isset($data->activity->subject)){
                $lists[$v]['activity_name'] = $data->activity->subject;
            }else{
                $lists[$v]['activity_name'] = '';
            }
            $lists[$v]['id'] = $v;
            $lists[$v]['games'] = Game::with('activity','type')->where('activity_id', $v)->orderBy('activity_id')->get();
        }


        $page = $request->input('page') ? $request->input('page') : 1;

        $paginator = new lPaginator(
            array_slice($lists, ($page - 1)*10, 10), count($lists), 10, $page, [
            'path'  => 'search',
            'query' => array('subject' => trim($data['subject'])),
        ]);


        return view('game.search')->with("lists", $paginator)->with("actions", $this->actions)
            ->with("wjtrUrl", $this->wjtrUrl)->with("subject",trim($data['subject']));
    }

    /**
     * 获取库存接口
     */
    public function postStock(Request $request)
    {
        $data = $request->input();
//        dd($data);

        if(isset($data['type']) && 'edit' ==$data['type']){
            $prizes = GamePrize::where('game_id', $data['game_id'])->get();
            $prize_ids = GamePrize::where('game_id', $data['game_id'])->get()->lists('id')->toArray();
            $stock = GameGoods::where('id', $data['id'])->first()->stock;
            if(in_array($data['id'], $prize_ids)){
                $num = GamePrize::where('game_id',$data['game_id'])->where('goods_id',$data['id'])->first()->num;
                $stock = $stock+$num;
            }
        }else{
            $stock = GameGoods::where('id', $data['id'])->first();
        }

        if($stock){
            return AjaxCallbackMessage($stock, true);
        }else{
            return AjaxCallbackMessage('没有找到数据', false);
        }
    }

    /**
     * 获取创建页面
     */
    public function getCreate()
    {
        $types  =GameType::get();
        $goods = GameGoods::get();
        return view('game.create')->with('types', $types)->with('goods', $goods);
    }


    /**
     * 获取编辑页面
     */
    public function getEdit(Request $request)
    {
        $data = $request->input();

        $game = Game::where('id', $data['id'])->get();
        $activity = Activity::where('id', $game->activity_id)->first();
        $types  =GameType::get();
        $prizes = GamePrize::where('game_id', $game->id)->orderBy('type', 'asc')->get();
        $arr = array('一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五');
        $goods = GameGoods::get();


        return view('game.edit')->with('activity', $activity)->with('game', $game)->with('types', $types)
            ->with('prizes', $prizes)->with('arr', $arr)->with('goods', $goods);
    }

    /**
     * 执行一个创建
     */
    public function postCreate(Request $request)
    {
        $data = $request->input();

        //判断是否有重复的特等奖，一等奖，二等奖，及三等奖
        $prize_types = array();
        $prize_goods = array();
        $prize_numbers = array();
        foreach($data as $k=>$v){
            if(strpos($k,'prize_type')!==false){
                $prize_types[] = $v;
            }
            if(strpos($k,'prize_goods')!==false){
                $prize_goods[] = $v;
            }
            if(strpos($k,'number')!==false){
                $prize_numbers[] = $v;
            }
        }
        foreach($prize_numbers as $k=>$v){
            if(!is_int($v+0) || ($v+0)<1){
                return AjaxCallbackMessage('至少存在一个奖品的数量不为正整数，请更正再提交',false);
            }
        }

        $times = array_count_values($prize_types);
//        dd($times);
        if(isset($times[0]) && $times[0]>1){
            return AjaxCallbackMessage('特等奖只能设置一个,请更正后，再提交',false);
        }


        if(isset($times[1]) && $times[1]>1){
            return AjaxCallbackMessage('一等奖只能设置一个,请更正后，再提交',false);
        }


        if(isset($times[2]) && $times[2]>1){
            return AjaxCallbackMessage('二等奖只能设置一个,请更正后，再提交',false);
        }

        if(isset($times[3]) && $times[3]>1){
            return AjaxCallbackMessage('三等奖只能设置一个,请更正后，再提交',false);
        }

        //判断一个游戏下面的奖项是否有重复的
        if(count($prize_goods)!=count(array_flip($prize_goods))){
            return AjaxCallbackMessage('一个游戏下面的奖品物品，不允许重复，请检查',false);
        }

        //判断是否提交了空的奖品物品
        if(in_array('', $prize_goods)){
            return AjaxCallbackMessage('至少存在一个奖品物品是，未选择，请更正再提交',false);
        }

        //判断是否提交了空奖品类型
        if(in_array('', $prize_types)){
            return AjaxCallbackMessage('至少存在一个奖品类型是，未选择，请更正再提交',false);
        }



        $list = Game::create(['activity_id'=>$data['activity_id'], 'type_id'=>$data['game_type'], 'title'=>$data['game_name']]);
        unset($data['activity_id'],$data['game_type'],$data['game_name'], $data['title'], $data['formType'], $data['_token']);
//        dd($data);
        $total = count($data);
        for($i=0;$i<$total/4;$i++){
            $arr = array_values(array_slice($data, $i*4, 4));
//            dd($arr);
            GamePrize::create(['game_id'=>$list->id, 'title'=>$arr[0], 'type'=>$arr[1], 'goods_id'=>$arr[2], 'num'=>$arr[3], 'left'=>$arr[3]]);
            //库存做相应的减少
            GameGoods::where('id', $arr[2])->decrement('stock', $arr[3]);;
        }


        return AjaxCallbackMessage('活动游戏创建成功', true, url('game/index'));
    }


    /**
     * 执行一个编辑
     */
    public function postEdit(ActRequest $request)
    {
        $data = $request->input();
        $game = Game::where('id', $data['id'])->first();
        if(0==$game->status){
            return AjaxCallbackMessage('该游戏已经使用了,不允许编辑', false);
        }
        Game::where('id', $data['id'])->update(['type_id'=>$data['game_type'], 'title'=>$data['game_name']]);
        unset($data['activity_id'],$data['game_type'],$data['game_name'], $data['formType'], $data['_token']);
        GamePrize::where('game_id', $data['id'])->delete();

        $total = count($data);
        for($i=0;$i<$total/3;$i++){
            $arr = array_slice($data, $i*3, 3);
            GamePrize::create(['game_id'=>$data['id'], 'type'=>$arr[0], 'goods_id'=>$arr[1], 'num'=>$arr[3],'left'=>$arr[3]]);
        }


        return AjaxCallbackMessage('编辑成功', true, url('game/index'));
    }


    /**
     * @param Request $request
     * 导出该次活动的获奖者名单
     */
    public function getExport(Request $request)
    {
        $data = $request->input();
        $games = Game::where('activity_id', $data['id'])->get();
        $totalPrizes = array();
        foreach($games as $k=>$v){
            $prizes = GamePrize::where('game_id', $v->id)->get()->toArray();
            $totalPrizes= array_merge($totalPrizes, $prizes);
        }


        $totalWinners = array();
        foreach($totalPrizes as $k=>$v){
            $winners = GameWinners::with('user', 'prize.game', 'prize.goods')->where('prize_id', $v['id'])->get()->toArray();
            $totalWinners = array_merge($totalWinners, $winners);
        }

        $activity = Activity::where('id', $data['id'])->first();
        $winnersInfo = array();
        foreach($totalWinners as $k=>$v){
            //游戏名
            if(isset($v['prize']['game']['title'])){
                $winnersInfo[$k]['game_name'] = $v['prize']['game']['title'];
            }else{
                $winnersInfo[$k]['game_name'] = '';
            }

            //奖项类型

            if(isset($v['prize']['type'])){
                if(0==$v['prize']['type']){
                    $winnersInfo[$k]['prize_type'] = '特等奖';
                }elseif(1==$v['prize']['type']){
                    $winnersInfo[$k]['prize_type'] = '一等奖';
                }elseif(2==$v['prize']['type']){
                    $winnersInfo[$k]['prize_type'] = '二等奖';
                }elseif(3==$v['prize']['type']){
                    $winnersInfo[$k]['prize_type'] = '三等奖';
                }elseif(4==$v['prize']['type']){
                    $winnersInfo[$k]['prize_type'] = '普通奖';
                }
            }else{
                $winnersInfo[$k]['prize_type'] = '';
            }

            //奖项名
            if(isset($v['prize']['title'])){
                $winnersInfo[$k]['prize_name'] = $v['prize']['title'];
            }else{
                $winnersInfo[$k]['prize_name'] = '';
            }

            //奖品物品
            if(isset($v['prize']['goods']['name'])){
                $winnersInfo[$k]['goods_name'] = $v['prize']['goods']['name'];
            }else{
                $winnersInfo[$k]['goods_name'] = '';
            }

            //注册用户名
            if(isset($v['user']['username'])){
                $winnersInfo[$k]['reg_username'] = $v['user']['username'];
            }else{
                $winnersInfo[$k]['reg_username'] = '';
            }
            //邮寄用的地址
            $winnersInfo[$k]['address'] = $v['address'];
            //邮寄用的用户名
            $winnersInfo[$k]['post_name'] = $v['name'];
            //邮寄用的电话
            $winnersInfo[$k]['post_tel'] = $v['tel'];
        }
        //表头
        $title = [["game_name" =>'游戏名', "prize_type" =>'奖项类型', "prize_name" =>'奖项名',"goods_name" =>'奖品物品',"reg_username" =>'注册时的用户名',"address" =>'邮寄用的地址',"post_name" =>'获奖人名称（邮寄用）',"post_tel" =>'电话（邮寄用）'],];
        $winnersInfo = array_merge($title, $winnersInfo);
        Excel::create('活动“'.$activity->subject.'”的获奖者名单', function($excel) use($winnersInfo) {
            $excel->sheet('获奖者名单', function($sheet) use($winnersInfo) {
                $sheet->rows($winnersInfo);
            });
        })->export('xls');
    }

    /**
     * 获取详情页面
     */
    public function getInfo(Request $request)
    {
        $data = $request->input();
        $activity = Activity::where('id', $data['id'])->first();
        $games = Game::with('prize')->where('activity_id', $data['id'])->get();
        $arr = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五');

        $totalPrizes = array();
        foreach($games as $k=>$v){
            $prizes = GamePrize::where('game_id', $v->id)->get()->toArray();
            $totalPrizes= array_merge($totalPrizes, $prizes);
        }

        $totalWinners = array();
        foreach($totalPrizes as $k=>$v){
            $winners = GameWinners::with('user', 'prize.game', 'prize.goods')->where('prize_id', $v['id'])->get()->toArray();
            $totalWinners = array_merge($totalWinners, $winners);
        }
        $types  =GameType::get();
        $goods = GameGoods::get();
//        dd($games[0]->prize[0]);


        return view('game.info')->with('activity', $activity)->with('types', $types)->with('goods', $goods)
            ->with('games', $games)->with('arr', $arr)->with('totalWinners', $totalWinners);
    }


    /**
     * 执行一个删除
     */
    public function postDelete(Request $request)
    {
        $data = $request->input();
        $games = Game::where('activity_id', $data['aid'])->get();
        foreach($games as $k=>$v){
            if(0==$v->status){
                return AjaxCallbackMessage('至少存在一个游戏已经使用了,不允许删除', false);
            }
        }

        foreach($games as $k=>$v){
            //恢复该游戏下的库存
            $prizes = GamePrize::where('game_id', $v->id)->get();

            foreach($prizes as $key=>$val){
                GameGoods::where('id', $val->goods_id)->increment('stock', $val->num);
            }

            Game::where('id', $v->id)->delete();
            GamePrize::where('game_id', $v->id)->delete();
        }

        return AjaxCallbackMessage('删除成功，该活动下所有游戏下的奖项也一起删除了', true);
    }
}